﻿namespace Zen.BlackBerry.Push.Repositories
{
	using System.Runtime.Caching;
	using Zen.BlackBerry.Push.DataAccess;

	public class CachingRepository : Repository
	{
		private MemoryCache _cache;

		public CachingRepository()
		{
		}

		public CachingRepository(ZenPushServiceEntities context)
			: base(context)
		{
		}

		public CachingRepository(string namedCache)
		{
			NamedCache = namedCache;
		}

		public CachingRepository(string namedCache, ZenPushServiceEntities context)
			: base(context)
		{
			NamedCache = namedCache;
		}

		protected string NamedCache
		{
			get;
			private set;
		}

		protected MemoryCache Cache
		{
			get
			{
				if (string.IsNullOrEmpty(NamedCache))
				{
					return MemoryCache.Default;
				}
				else
				{
					if (_cache == null)
					{
						_cache = new MemoryCache(NamedCache);
					}
					return _cache;
				}
			}
		}

		protected T GetCachedItem<T>(string key)
		{
			return (T)Cache.Get(GetCacheKey(key));
		}

		protected string GetCacheKey(string key)
		{
			return string.Format("{0}:{1}", GetType().Name, key);
		}
	}
}
